/////////////////////////////// AALITEM ///////////////////////////////
var aalItems = new Array();

var fillAALItem = function(data){
	$("#aalItemId").val(data == undefined ? "":data.id);
	$("#oldalItemId").val(data == undefined ? "":data.id);
	$("#aalItemName").val(data == undefined ? "":data.name);
	$("#aalItemHotkey").val(data == undefined ? "":data.hotkey);
	$("#aalItemLeft").val(data == undefined ? "":data.left);
	$("#aalItemTop").val(data == undefined ? "":data.top);
	$("#aalItemWidth").val(data == undefined ? "":data.width);
	$("#aalItemHeight").val(data == undefined ? "":data.height);

	// parent
	var parentId = 0;
	if(data != undefined)
		parentId = parseInt(data.parent);
	var aalItemParentCombo = "<select class='system' name='parent' size='1'>";	
	$.each(aalItems, function(index, entry) {
		// if data != undefined -> this is an exisitng AALItem
		// parent can't be modified any more.
		// user can just delete this AALItem and create new one.
		if(data == undefined){
			// new AALItem -> all parents are allowed
			aalItemParentCombo += "<option value='" + entry.id + "'";
			if(parentId == parseInt(entry.id))
				aalItemParentCombo += " selected";
			aalItemParentCombo += ">[" + entry.id + "] " + entry.name;
			aalItemParentCombo += "</option>";	
		} else {
			// existing AALItem -> only right parent is allowed
			if(parentId == parseInt(entry.id)){
				aalItemParentCombo += "<option value='" + entry.id + "' selected>[" + entry.id + "] " + entry.name + "</option>";	
			}
		}
		
		
	});
	aalItemParentCombo += "</select>";
	$("#aalItemParent").html(aalItemParentCombo);
	

	// template
	var templateCombo = "<select class='system' name='template' size='1'>";	
	$.each(templates, function(index, entry) {
		templateCombo += "<option value='" + entry.name + "'";
		if(data != undefined && data.template == entry.name)
			templateCombo += " selected";
		templateCombo += ">" + entry.name;
		templateCombo += "</option>";	
	});
	templateCombo += "</select>";
	$("#aalItemTemplate").html(templateCombo);

	// type
	var typeCombo = "<select class='system' name='type' size='1'>";	
	$.each(types, function(index, entry) {
		typeCombo += "<option value='" + entry.type + "'";
		if(data != undefined && data.type == entry.type)
			typeCombo += " selected";
		typeCombo += ">" + entry.type;
		typeCombo += "</option>";	
	});
	typeCombo += "</select>";
	$("#aalItemType").html(typeCombo);

	$('#aalItemSubmitter').attr("disabled", false);
	$('#modifyAALItemResult').html("");
};

var createAALItem = function(){
	fillAALItem();
	$('#systemModifierForm').removeClass('hidden');  // Show main window
	$('#systemModifierFormTitle').html('Create new system entry');  // Show main window
	$('#aalItemSubmitter').val('create');
};

var deleteAALItem = function(_aalItemId){
	$.ajax({
		dataType: 'json',
		url: '/ajax/deleteAALItem',
		data: {id: _aalItemId},
		beforeSubmit: function() {
			enableRefresh = false;
		},
		success: function(data){
			enableRefresh = true;
			alert(data.message);
			refreshAvailableAALItems();
		},
		error: function(ev) {
		}
	});
};

function doesAALItemExist(id){
	var exists = false;
	$.each(aalItems, function(index, entry) {
		var anExistingId = parseInt(entry.id);
		if(anExistingId == id){
			exists = true;
		}
	});
	return exists;
}

function checkNewAALItem(){
	var newId = parseInt($("#aalItemId").val());
	var oldId = parseInt($("#oldalItemId").val());
	var parentId = parseInt($("#aalItemParent").val());

	if(isNaN(oldId)){
		// It's a new aalItem
		// check newId for a valid int value
		if(isNaN(newId)){
			alert("Please enter a valid integer value for the 'new id' field!");
			return false;
		}

		// check if newId exists. It must not.
		if(doesAALItemExist(newId)){
			alert("The entered 'new id' field already exists. Please choose another id value!");
			return false;
		}
		
		// new id doesn't exists.
		// so this is a new, not existing aalItem.
		// everything seems to be ok, submit the form.
		
	} else {
		// it is an existing aalItem which should be updated
		// check oldId for a valid int value
		if(isNaN(oldId)){
			alert("Something went wrong. You tried to update an existing system entry but the hidden field 'oldId' could not be converted to an valid int value. Sorry, giving up!");
			return false;
		}

		// check if the oldId exists. Is have to exists.
		if(!doesAALItemExist(oldId)){
			alert("Something went wrong. You tried to update an existing system entry but the hidden field 'oldId' could not be found in the list of existing entries. Sorry, giving up");
			return false;
		}

		// it is an existing aalItem which should be updated
		// check newId for a valid int value
		if(isNaN(newId)){
			alert("Please enter a valid integer value for the 'new id' field!");
			return false;
		}

		// check if oldId == newId.
		if(newId == oldId){
			// this should be an property update on an existing aalItem
			// check if the newId exists. Is have to exists.
			if(!doesAALItemExist(newId)){
				alert("Something went wrong. You tried to update an existing system entry but the given new id could not be found. Sorry, giving up");
				return false;
			}
		} else {
			// this is an id switch. The newId should not exist.
			if(doesAALItemExist(newId)){
				alert("The entered 'new id' field already exists. Please choose another id value!");
				return false;
			}
		}
		
	}

	// hotkey
	if($("#aalItemHotkey").val() != ""){
		var hotkey = parseInt($("#aalItemHotkey").val());
		if(isNaN(hotkey) || hotkey < -1 || hotkey > 10){
			alert("Please enter a value between 0 and 9 for the 'hotkey' field or delete it!");
			return false;
		}
	}

	//left
	if($("#aalItemLeft").val() != ""){
		var value = parseFloat($("#aalItemLeft").val());
		if(isNaN(value) || value < 0.0 || value > 100.0){
			alert("Please enter a value between 0.0 and 100.0 for the 'left' field or delete it!");
			return false;
		}
	}

	//top
	if($("#aalItemTop").val() != ""){
		var value = parseFloat($("#aalItemTop").val());
		if(isNaN(value) || value < 0.0 || value > 100.0){
			alert("Please enter a value between 0.0 and 100.0 for the 'top' field or delete it!");
			return false;
		}
	}

	//width
	if($("#aalItemWidth").val() != ""){
		var value = parseFloat($("#aalItemWidth").val());
		if(isNaN(value) || value < 0.0 || value > 100.0){
			alert("Please enter a value between 0.0 and 100.0 for the 'width' field or delete it!");
			return false;
		}
	}

	//height
	if($("#aalItemHeight").val() != ""){
		var value = parseFloat($("#aalItemHeight").val());
		if(isNaN(value) || value < 0.0 || value > 100.0){
			alert("Please enter a value between 0.0 and 100.0 for the 'height' field or delete it!");
			return false;
		}
	}
	return true;
}

var saveAvailableAALItems = function(data){
	aalItems = new Array();
	$.each(data, function(index, entry) {
		aalItems.push(entry);
	});
};

var simulate = function(_sendButton){
	var _row = $(_sendButton).parent().parent();
	var id = _row.children()[0].firstChild.nodeValue;
	var selection = $(_row).children()[3].getElementsByTagName("select")[0];
	var viewType = 'show';
	for (i = 0; i < selection.length; ++i){
		if (selection.options[i].selected == true)
			viewType = selection.options[i].value;
	}
	var message = $(_row).children()[4].getElementsByTagName("input")[0].value;
	$.ajax({
		dataType: 'json',
		url: '/ajax/' + viewType,
		data: {itemId: id, message: message},
		success: function(ev) {
			//alert('OK');
		},
		error: function(ev) {
			alert('ERROR');
		}
	});
};

var refreshAvailableAALItemsHandler = function(data){

	saveAvailableAALItems(data);

	while ($('#AvailableAALitems tbody').children().length > 1) {
		$('#AvailableAALitems tr:nth-child(2)').remove();
	}

	var messageTypesCombo = "<select class='system' name='viewType' size='1'>";	
	$.each(messageTypes, function(index, entry) {
		messageTypesCombo += "<option>";
		messageTypesCombo += entry.type;
		messageTypesCombo += "</option>";	
	});
	messageTypesCombo += "</select>";

	$.each(data, function(index, entry) {
		var background = '';
		if(index % 2 == 0){
			background = " style='background-color: #ececec;'";
		}
		var row = $('<tr' + background + '>').appendTo('#AvailableAALitems');
	
		$('<td>')
			.html(entry.id)
			.prependTo(row);
		$('<td>')
			.html(entry.name +  " ")
			.appendTo(row);
		$('<td>')
			.html(getParentName(entry.parent) +  " ")
			.appendTo(row);
		$('<td>')
			.html(messageTypesCombo)
			.appendTo(row);
		$('<td>')
			.html("<input class='system' type='text' size='30'/> <input type='button' name='send' value='send' onClick='simulate(this);'>")
			.appendTo(row);
			if(entry.id != 0){
				$("<td width='50px;'>")
				.addClass('action')
				.html('edit')
				.click(function() {
					$('#systemModifierForm').removeClass('hidden');  // Show main window
					$('#systemModifierFormTitle').html('Modify system entry id:' + entry.id);  // Show main window
					$('#aalItemSubmitter').val('update');
					fillAALItem(entry);
				})
				.appendTo(row);
			}
			if(entry.id != 0){
				$("<td width='50px;'>")
				.addClass('action')
				.html('delete')
				.click(function() {
					deleteAALItem(entry.id);
				})
				.appendTo(row);
			}
	});
	enableRefresh = true;
};

function getParentName(_parentId){
	var parentName = "";
	$.each(aalItems, function(index, entry) {
		if(entry.id == _parentId)
			parentName = entry.name;
	});
	return parentName;
}

var refreshAvailableAALItems = function(){
	$.ajax({
		dataType: 'json',
		url: '/ajax/getAvailableAALItems',
		beforeSubmit: function() {
			enableRefresh = false;
		},
		success: refreshAvailableAALItemsHandler,
		error: function(ev) {
	}
	});
};

/////////////////////////////// AALITEM END ///////////////////////////////

$(document).ready(function() {
	$('#systemModifier').ajaxForm({
		dataType: 'json',
		beforeSubmit: function() {
			var everythingIsOk = checkNewAALItem();
			if(everythingIsOk){
				enableRefresh = false;
				$('#aalItemSubmitter').attr("disabled", true);
			}
			else
				return false;
		},
		success: function(data){
			var $out = $('#modifyAALItemResult');

			$out.removeClass('errorMsg');
			$out.removeClass('warnMsg');
			if(data.status = 'WARN'){
				$out.addClass('warnMsg');
			} else if(data.status = 'ERROR'){
				$out.addClass('errorMsg');
			}

			$out.append(data.message);
			refreshAvailableAALItems();
		}
	});
});